﻿using ETA.ClientService;
using ETA.Common;
using ETA.DomainEnum;
using ETA.Dtos;
using ETA.Entity;
using ETA.IService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace ETA.Web.Controllers
{
    public class UserController : BaseController
    {

        private static IUserService _IUserService { set; get; }
        private static IReferrerLogService _IReferrerLogService { set; get; }

        public UserController(IUserService service, IReferrerLogService IReferrerLogService)
        {
            _IUserService = service;
            _IReferrerLogService = IReferrerLogService;
        }

        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetAllUsers()
        {
            Logger.Log.Info("测试日志");
            return null;
        }

        /// <summary>
        /// 新用户注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register(UserDto userDto)
        {
            var createUserResponse = new CreateUserResponse();
            var err = string.Empty;

            if (!CheckNum(userDto.CheckNum, userDto.Mobile))
            {
                err += "手机验证码输入错误\r";
            }

            if (_IUserService.CheckMobile(userDto.Mobile))
            {
                err += "该号码已经被其他用户使用\r";
            }

            if (_IUserService.CheckEmail(userDto.Email))
            {
                err += "该邮箱已经被其他用户使用\r";
            }

            if (!string.IsNullOrEmpty(err))
            {
                createUserResponse.Result.IsSuccess = false;
                createUserResponse.Result.ErrMessage = err;
                return JsonWithDate(createUserResponse);
            }

            if (ModelState.IsValid)
            {
                var queryRolerResponse = _IUserService.QueryRoler(new QueryRolerRequest());
                if (queryRolerResponse.Result.IsSuccess)
                {
                    var shiXiSheng = queryRolerResponse.Rolers.First(q => q.RolerName == "实习生");
                    userDto.UserId = Guid.NewGuid().ToString();
                    userDto.Rolers = new List<Roler>() { shiXiSheng };
                    //userDto.Password = CommHelper.Base64Encrypt(userDto.Password);
                    var createUserReq = new CreateUserRequest
                    {
                        UserDto = userDto
                    };
                    createUserResponse = _IUserService.AddUser(createUserReq);
                    if (createUserResponse.Result.IsSuccess)
                    {
                        StausAdd(createUserResponse.UserDto);//状态序列化
                        if (!string.IsNullOrEmpty(userDto.ExpanderId))
                        {
                            var kuaiCheZhiYou = UserBll.GetCompltetUserInfo(userDto.ExpanderId);
                            if (kuaiCheZhiYou != null&&kuaiCheZhiYou.IsReferrer=="1")//信息存在且是快车之友
                            {
                                var referrer = UserBll.GetCompltetUserInfo(createUserResponse.User.UserId);
                                var createLogResponse = _IReferrerLogService.CreateReferrerLog(new CreateReferrerLogRequest
                                {
                                    ReferrerLog = new ReferrerLog
                                    {
                                        UserId = kuaiCheZhiYou.UserId,
                                        UserName = kuaiCheZhiYou.UserName,
                                        Referrer = referrer,
                                        Point = Config.ReferrerPoint//推荐积分
                                    }
                                });
                                if (!createLogResponse.Result.IsSuccess)
                                {
                                    Logger.Log.Error(string.Format("推荐失败,推荐人id:{0}，被推荐人id:{1}", userDto.ExpanderId, createUserResponse.User.UserId));
                                }
                            }
                            else
                            {
                                Logger.Log.Error(string.Format("推荐人ID 不存在{0}", userDto.ExpanderId));
                            }
                        }
                    }
                }
            }
            return JsonWithDate(createUserResponse);
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ModifyUserInfo(UserDto userDto)
        {
            var user = UserBll.GetCompltetUserInfo(CurrentUser.UserId); 

            var modifyUserResponse = new ModifyUserResponse();
            var err = string.Empty;

            if (userDto.Mobile != user.Mobile && !CheckNum(userDto.CheckNum, userDto.Mobile))
            {
                err += "手机验证码输入错误\r";
            }

            if (userDto.Mobile != user.Mobile && _IUserService.CheckMobile(userDto.Mobile))
            {
                err += "该号码已经被其他用户使用\r";
            }

            if (userDto.Email != user.Email && _IUserService.CheckEmail(userDto.Email))
            {
                err += "该邮箱已经被其他用户使用\r";
            }

            if (!string.IsNullOrEmpty(err))
            {
                modifyUserResponse.Result.IsSuccess = false;
                modifyUserResponse.Result.ErrMessage = err;
                return JsonWithDate(modifyUserResponse);
            }

            if (ModelState.IsValid)
            {
                FillModifyUser(user, userDto);
                modifyUserResponse = _IUserService.ModifyUser(new ModifyUserRequest { User = user });
            }
            return JsonWithDate(modifyUserResponse);
        }

        private void FillModifyUser(User user, UserDto userDto)
        {
            if (user.Email != userDto.Email)
            {
                user.Email = userDto.Email;
            }
            if (user.Mobile != userDto.Mobile)
            {
                user.Mobile = userDto.Mobile;
            }
            if (user.QQ != userDto.QQ)
            {
                user.QQ = userDto.QQ;
            }
            if (user.IsMarried != userDto.IsMarried)
            {
                user.IsMarried = userDto.IsMarried;
            }
            if (user.Age != userDto.Age)
            {
                user.Age = userDto.Age;
            }

            if (user.Height != userDto.Height)
            {
                user.Height = userDto.Height;
            }

            if (user.Weight != userDto.Weight)
            {
                user.Weight = userDto.Weight;
            }

            if (user.EyeGlass != userDto.EyeGlass)
            {
                user.EyeGlass = userDto.EyeGlass;
            }

            if (user.EyeLeft != userDto.EyeLeft)
            {
                user.EyeLeft = userDto.EyeLeft;
            }

            if (user.EyeRight != userDto.EyeRight)
            {
                user.EyeRight = userDto.EyeRight;
            }

            if (user.IsGotpassport != userDto.IsGotpassport)
            {
                user.IsGotpassport = userDto.IsGotpassport;
            }

            if (user.HasAbroadExperience != userDto.HasAbroadExperience)
            {
                user.HasAbroadExperience = userDto.HasAbroadExperience;
            }

        }
        /// <summary>
        /// 检测手机是否已经被使用
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public ActionResult CheckMobile(string mobile)
        {
            var res = _IUserService.CheckMobile(mobile);
            return JsonWithDate(res);
        }

        /// <summary>
        /// 检测邮箱是否已经被使用
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public ActionResult CheckEmail(string email)
        {
            var res = _IUserService.CheckEmail(email);
            return JsonWithDate(res);
        }

        /// <summary>
        /// 验证码发送
        /// </summary>
        /// <param name="checkNum"></param>
        /// <returns></returns>
        public ActionResult SendCheckNum(string mobile)
        {
            var res = new Response();
            var isExist = _IUserService.CheckMobile(mobile);
            if (isExist)
            {
                res.Result.ErrMessage = "该号码已经被其他用户使用";
                res.Result.IsSuccess = false;
                return JsonWithDate(res);
            }
            var checkNum = _IUserService.SendCheckNum(mobile);
            if (!string.IsNullOrEmpty(checkNum))
            {
                res.Result.IsSuccess = true;
                Session["CheckNum" + mobile] = checkNum;
                res.Result.Message = checkNum;
            }
            else
            {
                res.Result.IsSuccess = false;
                res.Result.ErrMessage = "发送失败";
            }
            return JsonWithDate(res);
        }


        /// <summary>
        /// 验证码检查
        /// </summary>
        /// <param name="checkNum"></param>
        /// <returns></returns>
        public ActionResult ActionCheckNum(string checkNum, string mobile)
        {
            return JsonWithDate(CheckNum(checkNum, mobile));
        }

        /// <summary>
        /// 验证码检查
        /// </summary>
        /// <param name="checkNum"></param>
        /// <returns></returns>
        private bool CheckNum(string checkNum, string mobile)
        {
            var sessionCheckNum = Session["CheckNum" + mobile];
            if (sessionCheckNum != null &&
                checkNum.Equals(sessionCheckNum.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="user"></param>
        /// <param name="rememberMe"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(string userName, string passWord, bool rememberMe = true)
        {
            var res = new Response();
            if (ModelState.IsValid)
            {
                var req1 = new QueryUserRequest
                  {
                      User = new User
                      {
                          Email = userName
                      }
                  };
                var req2 = new QueryUserRequest
                {
                    User = new User
                    {
                        Mobile = userName
                    }
                };

                var req3 = new QueryUserRequest
                {
                    User = new User
                    {
                        LoginName = userName
                    }
                };
                QueryUserResponse response = null;
                var response1 = _IUserService.QueryUser(req1);
                var response2 = _IUserService.QueryUser(req2);
                var response3 = _IUserService.QueryUser(req3);
                passWord = CommHelper.Base64Encrypt(passWord);
                if (response1.Result.IsSuccess && response1.Users.Any())
                {
                    if (response1.Users.FirstOrDefault().Password == passWord)
                    {
                        res.Result.IsSuccess = true;
                        response = response1;
                    }
                }
                else
                    if (response2.Result.IsSuccess && response2.Users.Any())
                    {
                        if (response2.Users.FirstOrDefault().Password == passWord)
                        {
                            res.Result.IsSuccess = true;
                            response = response2;
                        }
                    }
                    else
                        if (response3.Result.IsSuccess && response3.Users.Any())
                        {
                            if (response3.Users.FirstOrDefault().Password == passWord)
                            {
                                res.Result.IsSuccess = true;
                                response = response3;
                            }
                        }
                if (!res.Result.IsSuccess)
                {
                    res.Result.ErrMessage = "您输入的用户名或者密码错误";
                }
                else
                {
                    var userDto = response.DtoUsers.FirstOrDefault();
                    if (!userDto.IsDelete)
                    {
                        StausAdd(userDto);
                        res.Result.Message = userDto.Rolers.FirstOrDefault().Url;
                    }
                    else
                    {
                        res.Result.IsSuccess = false;
                        res.Result.ErrMessage = "您的帐号已经被暂停使用";
                    }
                }

            }
            return JsonWithDate(res);
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOut()
        {
            Session.Remove("userInfo");
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        //登录状态保持
        private void StausAdd(UserDto user, bool rememberMe = true)
        {
            var roler = user.Rolers.First();
            var simpleUserDto = new SimpleUserDto
            {
                LoginName = user.LoginName,
                UserId = user.UserId,
                UserName = user.UserName,
                RolerName = roler.RolerName,
                Url = roler.Url,
                IsAbroad = user.RegistrationBind != null && user.RegistrationBind.IsDelete == false //表示已出国
            };
            #region 登录状态保持
            int cookieTime = Config.ExpirationTime;

            Session["userInfo"] = simpleUserDto;
            FormsAuthentication.SetAuthCookie(simpleUserDto.UserName, rememberMe);
            //票据
            string data = string.Empty;
            if (user != null)
            {
                user.Password = "*********************";
                //if (user.RegistrationMainForms.Any())
                //{
                //    user.RegistrationMainForms.FirstOrDefault().User = null;//TODO 此处会迭代序列话 出错 后期寻求解决方案
                //}
                data = (new JavaScriptSerializer()).Serialize(simpleUserDto);
            }
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                 2, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(cookieTime), true, data);

            // 根据加密结果创建登录Cookie
            string cookieValue = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
            cookie.HttpOnly = true;
            cookie.Secure = FormsAuthentication.RequireSSL;
            cookie.Domain = FormsAuthentication.CookieDomain;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.Expires = DateTime.Now.AddMinutes(cookieTime);

            // 写登录Cookie
            Response.Cookies.Remove(cookie.Name);
            Response.Cookies.Add(cookie);
            ///
            #endregion
        }

        /// <summary>
        /// 当前登录用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AjaxGetCurrentUser()
        {
            return JsonWithDate(base.CurrentUser);
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <returns></returns>
        public ActionResult Getpassword()
        {
            return View();
        }

        /// <summary>
        /// 找回密码
        /// </summary>
        /// <param name="strNum">邮箱或者手机</param>
        /// <param name="type">0 是手机  1是邮箱</param>
        /// <returns></returns>
        public ActionResult GetPasswordAction(string strNum, int type)
        {
            var response = _IUserService.GetPassword(strNum, (GetpwdType)type);
            return Json(response);
        }

    }
}
